# coding=utf-8

from flask import render_template, request, flash, current_app, session, jsonify
from config import config
from . import auth


@auth.before_request
def bef_request():
    user_agent = request.headers.get('User-Agent')  # 客户端系统相关信息
    current_app.logger.info('客户端系统信息: %s', user_agent)
    user_ip = request.remote_addr  # 客户端的IP地址
    current_app.logger.info('客户端IP地址: %s', user_ip)


@auth.after_request
def aft_request(param):
    pass
    return param


@auth.route('/login', methods=['GET', 'POST'])
def login():
    session.clear()  # 退出时清空session
    if request.method == 'POST':
        username = request.form['username']
        # current_app.logger.info("------------------username" + username)
        password = request.form['password']
        # current_app.logger.info("------------------password" + password)
        login_username = config['default'].LOGIN_USERNAME
        login_password = config['default'].LOGIN_PASSWORD
        # current_app.logger.info("------------------login_username" + login_username)
        # current_app.logger.info("------------------login_password" + login_password)
        if username == login_username and password == login_password:
            session['username'] = username
            # resp = make_response(redirect(url_for('main.index')))
            # resp.set_cookie('username', username)
            # return resp
            # render_template(redirect(url_for('main.index')))
            # render_template('index.html', username=session['username'], current_time=datetime.utcnow())
            return jsonify({'status': '0', 'errmsg': '登录成功！'})
        else:
            render_template('login.html')
            flash('username or password is invalid, please try again')
            return jsonify({'status': '1', 'errmsg': '用户名或密码错误！'})
    else:
        return render_template('login.html')
